import { Body, Controller, Get, Param, Post, UseGuards, Headers, Query } from '@nestjs/common';
import { ConfigDto, VisualChatDto } from './dto/visualChat.dto';
import { VisualChatService } from './visualChat.service';
// import RedisSingleton from 'src/config/redis';
import { ERROR_CODE, ERROR_MESSAGE, getResponse } from 'src/common/const/const';
import { AuthService } from 'src/services/Auth';
import { getRagData } from 'src/common/api/peiban';
import { VipUsageService } from 'src/vipUsage/vipUsage.service';
import { VipInfoService } from 'src/vipInfo/vipInfo.service';
import { NonVipAiChatLimit } from 'src/common/const/const';
import { serviceErrorLog } from "src/common/out/logger/access.logger";

// @UseGuards(RolesGuard)
@Controller('visualChat')
export class VisualChatController {
  constructor(
    private readonly visualChatService: VisualChatService,
    private readonly authService: AuthService,
    private readonly vipInfoService: VipInfoService,
    private readonly vipUsageService: VipUsageService
  ) { }

  @Post('/config')
  // @Roles('admin')
  async getConfig(@Body() configDto: ConfigDto, @Headers() headers: any) {
    const userInfo = this.authService.checkAuth(headers);
    if (!userInfo) {
      return getResponse(ERROR_CODE.VERIFY_EXPIRE, ERROR_MESSAGE[ERROR_CODE.VERIFY_EXPIRE], {})
    }
    // // 默认分配一个唯一用户Id
    let response = await this.visualChatService.findVisualMan(userInfo.userid);
    return getResponse(0, "success", response);
  }

  @Post('/chat')
  // @Roles('admin')
  async chat(@Body() visualChatDto: VisualChatDto, @Query() queryParams: any, @Headers() headers: any) {
    // 兼容微信来源
    // const token = headers.authorization || "";
    // 默认分配一个唯一用户Id
    let userInfo = this.authService.checkAuth(headers);
    if (!userInfo) {
      return getResponse(ERROR_CODE.VERIFY_EXPIRE, ERROR_MESSAGE[ERROR_CODE.VERIFY_EXPIRE], {})
    }
    const userid = userInfo.userid
    let response = await this.visualChatService.chatWithVisualMan({ userid: userInfo.userid, ...visualChatDto });
    if (response && response.answer == "") {
      return getResponse(0, ERROR_CODE.INTERNAL_FAIL, ERROR_MESSAGE[ERROR_CODE.INTERNAL_FAIL]);
    }
    const textMsg = {
      type: "text",
      content: response.answer
    }
    const imgMsg = {
      type: "audio",
      content: "https://lovetalkon.tos-cn-beijing.volces.com/audios/1734920311726-74qhpvk.mp3"
    }
    // 更新 vip 功能使用次数
    await this.vipUsageService.addVisualChatCnt(userid)
    return getResponse(0, "success", [textMsg,imgMsg]);
  }
}
